/**  定义Banner相关的接口 */
const express = require("express");
const router = express.Router();
const Response = require("../utils/Response.js");
// 引入mysql连接池
const pool = require("../utils/db.js");


// 添加轮播
router.post("/banner/add", (req, resp)=>{
  let obj=req.body
  let sql = "insert into carousel set ?"
  pool.query(sql, [obj], (error, result)=>{
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    // 注册成功
    resp.send(Response.ok());
  })
});

// 查询轮播图列表
router.get("/banner/list",async (req, resp)=>{
  let { page, pagesize } = req.query;
  let startIndex = (page - 1) * pagesize;
  let size = parseInt(pagesize);
  try{
    let sql = "select * from carousel limit ?,?"
    let result=await pool.querySync(sql, [startIndex,size])
    let sql2="select count(*) as total from carousel"
    let result2=await pool.querySync(sql2)
    resp.send(
      Response.ok({result,total:result2[0].total,pageIndex:page,pageSize:pagesize})
    )
  }
  catch(error){
    resp.send(Response.error(error))
  }
});

// 通过id查询轮播
router.get("/banner/ById", (req, resp)=>{
  let obj=req.query
  let sql = "select * from carousel where carousel_id=?"
  pool.query(sql, [obj.carousel_id], (error, result)=>{
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    // 注册成功
    resp.send(Response.ok({result}));
  })
});


// 修改轮播
router.post("/banner/update", (req, resp)=>{
  let obj=req.body
  let sql = "update  carousel set ? where carousel_id=?"
  pool.query(sql, [obj,obj.carousel_id], (error, result)=>{
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    // 注册成功
    resp.send(Response.ok());
  })
});

// 将router对象导出
module.exports = router;